package com.ljb.downloadmanager;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.Arrays;

/**
 * Created by lijianbin on 2017/2/6.
 */
public class DownloadManagerReceiver extends BroadcastReceiver {
    private static final String TAG = "DownloadManagerReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            Log.e(TAG, "onReceive: 用户点击了通知");
            // 点击下载进度通知时, 对应的下载ID以数组的方式传递
            long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            Log.e(TAG, "onReceive: " + "ids: " + Arrays.toString(ids));
        } else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            Log.e(TAG, "onReceive: 接收到下载完成的广播");
            /**
             * 获取下载完成对应的下载ID, 这里下载完成指的不是下载成功, 下载失败也算是下载完成,
             * 所以接收到下载完成广播后, 还需要根据 id 手动查询对应下载请求的成功与失败.
             */
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
            Log.e(TAG, "onReceive: id:" + id);
            // 根据获取到的ID，查询是否下载成功
            DMHelper.query(id);
        }
    }
}
